package javax.per.toolkit.search;
import java.io.BufferedWriter;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.Vector;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import javax.per.toolkit.file.FileUtil;
import javax.per.toolkit.sys.ClipboardUtil;
import javax.per.toolkit.tools.Fun;
import javax.per.toolkit.tools.Log;
import javax.per.toolkit.tools.msg.Msg;

import org.apache.tools.zip.ZipEntry;
import org.apache.tools.zip.ZipFile;

import tools.Env;
import static javax.per.toolkit.tools.Fun.pl;


public class ffijs {
	
	public static String filename=null;
	/**
	 * @param args
	 * @throws IOException 
	 */
	public static void main(String[] args) throws IOException {
		for(String str:args){
			if(str.equalsIgnoreCase("-update")){
				preffijs(null);
				return;
			}
		}
		filename=Fun.getConsoleString();
		if(filename==null||filename.trim().length()==0){
			return;
		}
		filename=filename.toUpperCase().trim();
		if(FileUtil.getExtension(filename).endsWith("class")||FileUtil.getExtension(filename).endsWith("java")){
			filename=FileUtil.getFileName(filename);
		}
		if(filename.toUpperCase().endsWith(".CLASS")){
			filename=filename.substring(0,filename.length()-".CLASS".length());
			Log.getLogger().debug(filename);
		}
		filename=filename.replaceAll("\\.", "/");
		Vector<File> result=new Vector<File>();
		String pf=Env.get("tempFileDir").replaceAll("\\\\", "/")+"/ffijs";
		File[] fs=new File(pf).listFiles();
		ExecutorService ser=Executors.newFixedThreadPool(3);
		for(File f:fs){
			ser.submit(new RunFindFileInJar(f,result));
		}
		ser.shutdown();
		while(!ser.isTerminated()){
			try {
				Thread.sleep(100);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		if(result.size()>0){
			if(result.size()==1){
				List<File> fileList=result;
				ClipboardUtil.setFiles(fileList);
				Fun.setSeparator("\n");
				pl(result);
			}else{
				Fun.setShowLineNumber(true);
				Fun.setSeparator("\n");
				pl(result);
				
				int line=Fun.getConsoleInt();
				ClipboardUtil.setFile(result.get(line).getAbsolutePath());
			}
			
			
		}else{
			pl(Msg.get("NF"));
		}
	}
	
	private static class RunFindFileInJar implements Runnable{
		File f;
		Vector<File> list;
		public RunFindFileInJar(File f,Vector<File> list){
			this.f=f;
			this.list=list;
		}

		@Override
		public void run() {
			String content = "";
			try {
				content = FileUtil.getContent(f.getAbsolutePath(),"utf-8");
			} catch (IOException e) {
				e.printStackTrace();
			}
			if(content.contains(filename))
				list.add(new File(FileUtil.getFileName(f.getName()).replaceAll("__", "/").replaceFirst("/", "\\:/")));
		}
		
	}
	
	public static void preffijs(String[] args) {
		File pf=new File(Env.get("tempFileDir").replaceAll("\\\\", "/")+"/ffijs");
		if(pf.exists()){
			if(pf.isDirectory())
				FileUtil.deleteFolder(pf.getAbsolutePath());
			else
				pf.delete();
		}
		String dir=Env.get("jardir");
		String dirs[]=dir.split(";");
		List<File> fileList=new ArrayList<File>();
		for(String d:dirs)
		{
			fileList.addAll(Fun.getSubFiles(d, new String[]{".*\\.jar"}));
		}
		
		ExecutorService ser=Executors.newFixedThreadPool(3);
		for(File f:fileList){
			ser.submit(new PreFindFileInJar(f));
		}
		ser.shutdown();
		while(!ser.isTerminated()){
			try {
				Thread.sleep(100);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}
}

class PreFindFileInJar implements Runnable{
	File s;
	BufferedWriter bw;
	public PreFindFileInJar(File f){
		this.s=f;
	}
	
	public String getPath(File f){
		String str=Env.get("tempFileDir").replaceAll("\\\\", "/")+"/ffijs/"+f.getAbsolutePath().replaceAll("\\\\", "/").replaceAll("/", "__").replaceFirst(":", "")+".mir";
		return str;
	}

	@Override
	public void run() {
		Log.getLogger().debug(s.getAbsolutePath());
		String lineS=System.getProperty("line.separator");
		try {
			bw=FileUtil.getAppendWriter(this.getPath(this.s),"utf-8");
		} catch (IOException e) {
			e.printStackTrace();
		}
		ZipFile zipfile = null;
		try {
			zipfile = new ZipFile(s,
					System.getProperty("sun.jnu.encoding"));
		} catch (IOException e) {
			e.printStackTrace();
		}
		@SuppressWarnings("rawtypes")
		Enumeration enu = zipfile.getEntries();
		if (enu == null)
			return;
		while (enu.hasMoreElements()) {
			ZipEntry ze = (ZipEntry) enu.nextElement();
			try {
				bw.append(ze.getName().replaceAll("\\\\", "/").toUpperCase()+lineS);
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		try {
			bw.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
}
